package com.example.servlet.user;

import com.example.entity.User;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.*;
import java.nio.file.*;

@WebServlet("/user_upload")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 1, // 1MB
        maxFileSize = 1024 * 1024 * 5,      // 5MB
        maxRequestSize = 1024 * 1024 * 10   // 10MB
)
public class uUploadServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 获取当前用户ID
        User user = (User) request.getSession().getAttribute("user");
        int userId = user.getU_id();

        // 获取上传的文件
        Part filePart = request.getPart("photo");
        String fileName = userId + ".jpg"; // 使用用户ID命名

        // 硬编码开发阶段路径（仅限调试用）
        String devUploadPath = "C:\\study\\java\\TicketOrder\\src\\main\\webapp\\static\\images";
        File uploadDir = new File(devUploadPath);

        if (!uploadDir.exists()) {
            uploadDir.mkdirs(); // 创建目录
        }

        // 写入文件到开发目录
        filePart.write(devUploadPath + File.separator + fileName);

        System.out.println("文件已保存至：" + devUploadPath + "\\" + fileName);

        // 重定向回个人中心页面
        response.sendRedirect("user_profile");
    }
}
